//
//  JKShareManager.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/15.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import JKAlertX

enum JKShareType {
    
    case wechatSession   // 微信朋友
    case wechatTimeline  // 微信朋友圈
    case wechatFavorite  // 微信收藏
    case mobileQQ        // QQ
    case qzone           // QQ空间
    case sina            // 新浪微博
}

class JKShareManager: NSObject {
    
    /** 单例 */
    public static let shared = JKShareManager()
    
    /** 分享到微信实例化对象 */
    private var sendToWXReq: SendMessageToWXReq?

    /**
     *  通过第三方分享内容
     *
     *  @param url         分享的链接
     *  @param text        分享的标题
     *  @param description 分享的详情（微信中没有这个，可以为空）
     *  @param imageUrl    分享中图片的url （微博分享中，这个url的图片大小不能超过32k）
     *  @param type        分享的途径或方式
     */
    public class func share(url: String?, text: String?, description: String?, imageUrl: String?, shareType: JKShareType) {
        
        guard let _ = url else { return }
        
        switch shareType {
            
        case .wechatSession: // 微信朋友
            
            JKShareManager.shared.shareToWeiChat(url: url!, text: text, description: description, imageUrl: imageUrl, shareType: WXSceneSession)
            
            break
            
        case .wechatTimeline: // 微信朋友圈
            
            JKShareManager.shared.shareToWeiChat(url: url!, text: text, description: description, imageUrl: imageUrl, shareType: WXSceneTimeline)
            
            break
            
        case .wechatFavorite: // 微信收藏
            
            JKShareManager.shared.shareToWeiChat(url: url!, text: text, description: description, imageUrl: imageUrl, shareType: WXSceneFavorite)
            
            break
            
        case .mobileQQ: // QQ
            
            break
            
        case .qzone: // QQ空间
            
            break
            
        case .sina: // 新浪微博
            
            JKShareManager.shared.shareToSina(url: url!, text: text, description: description, imageUrl: imageUrl)
            
            break
        }
        
    }
    
    /** 分享到微信 */
    private func shareToWeiChat(url: String, text: String?, description: String?, imageUrl: String?, shareType: WXScene) {
        
        if !(WXApi.isWXAppInstalled()) || !(WXApi.isWXAppSupport()) {
            
            let _ = JKAlertView(title: nil, message: "未安装微信，要下载安装吗？", style: JKAlertStylePlain).addAction(JKAlertAction(title: "取消", style: JKAlertActionStyleCancel, handler: { (action) in
                
            }))?.addAction(JKAlertAction(title: "确定", style: JKAlertActionStyleDefault, handler: { (action) in
                
                if UIApplication.shared.canOpenURL(URL(string: WXApi.getWXAppInstallUrl())!) {
                    UIApplication.shared.openURL(URL(string: WXApi.getWXAppInstallUrl())!)
                }
            }))?.show()
            
            return
        }
        
        let message = WXMediaMessage()
        message.title = (text != nil) ? text! : " "
        message.description = (description != nil) ? description! : " "
        message.mediaTagName = "WECHAT_TAG_JUMP_SHOWRANK"
        
        if (imageUrl != nil) {
            
            if let imgURL = URL(string: imageUrl!) {
                
                // 注意线程处理
                if let imgData = try? Data(contentsOf: imgURL) {
                    
                    if (imgData.count < 32 * 1024) {
                        
                        if let image = UIImage(data: imgData) {
                            
                            message.setThumbImage(image)
                        }
                    }
                }
            }
        }
        
        let webpage = WXWebpageObject()
        webpage.webpageUrl = url
        message.mediaObject = webpage
        
        self.sendToWXReq = nil
        self.sendToWXReq = SendMessageToWXReq()
        self.sendToWXReq?.bText = false
        self.sendToWXReq?.message = message
        
        self.sendToWXReq?.scene = Int32(shareType.rawValue)
        WXApi.send(self.sendToWXReq!)
    }
    
    /** 分享到微信 */
    private func shareToSina(url: String, text: String?, description: String?, imageUrl: String?) {
        
        //    [WeiboSDK enableDebugMode:YES]
        WeiboSDK.registerApp(JKWeiboAppKey)
        
        let request = WBAuthorizeRequest.request() as! WBAuthorizeRequest
        request.redirectURI = "http://weibo.com/1849434443/profile?topnav=1&wvr=6"
        request.scope = "all"
        
        let message = WBMessageObject.message() as! WBMessageObject
        let webpage = WBWebpageObject.object() as! WBWebpageObject//WBWebpageObject object]
        webpage.objectID = "identifier1"
        webpage.title = NSLocalizedString(text!, comment: "")
        webpage.description = description
        
        
        if (imageUrl != nil) {
            
            if let imgURL = URL(string: imageUrl!) {
                
                // 注意线程处理
                if let imgData = try? Data(contentsOf: imgURL) {
                    
                    if (imgData.count < 32 * 1024) {
                        
                        webpage.thumbnailData = imgData
                    }
                }
            }
        }
        
        webpage.webpageUrl = url
        message.mediaObject = webpage
        
        let sendMessagerequest = WBSendMessageToWeiboRequest.request(withMessage: message) as! WBSendMessageToWeiboRequest
        sendMessagerequest.userInfo = ["ShareMessageFrom": "SendMessageToWeiboViewController",
                                       "Other_Info_1": 123,
                                       "Other_Info_2": ["obj1", "obj2"],
                                       "Other_Info_3": ["key1": "obj1", "key2": "obj2"]]
        request.shouldOpenWeiboAppInstallPageIfNotInstalled = false
        
        WeiboSDK.send(sendMessagerequest)
    }
    
    /*
     - (void)shareToQQ:(NSString *)url text:(NSString *)text description:(NSString *)description image:(NSString *)imageUrl {
     [[TencentOAuth alloc] initWithAppId:kQqAppId andDelegate:(id<TencentSessionDelegate>)self]
     
     QQApiNewsObject *newsObj = [QQApiNewsObject
     objectWithURL :[NSURL URLWithString:url]
     title: text
     description :description
     previewImageURL:[NSURL URLWithString:imageUrl]]
     SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj]
     //将内容分享到qq
     //QQApiSendResultCode sent = [QQApiInterface sendReq:req]
     //将内容分享到qzone
     QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req]
     
     [self handleSendResult:sent]
     
     }
     
     - (void)shareToQzone:(NSString *)url text:(NSString *)text description:(NSString *)description image:(NSString *)imageUrl {
     
     [[TencentOAuth alloc] initWithAppId:kQqAppId andDelegate:(id<TencentSessionDelegate>)self]
     QQApiNewsObject *newsObj = [QQApiNewsObject
     objectWithURL :[NSURL URLWithString:url]
     title: text
     description :description
     previewImageData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]]
     SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj]
     //将内容分享到qq
     QQApiSendResultCode sent = [QQApiInterface sendReq:req]
     //将内容分享到qzone
     //    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req]
     
     [self handleSendResult:sent]
     }
     
     - (void)handleSendResult:(QQApiSendResultCode)sendResult
     {
     switch (sendResult)
     {
     case EQQAPIAPPNOTREGISTED:
     {
     UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]
     [msgbox show]
     //            [msgbox release]
     
     break
     }
     case EQQAPIMESSAGECONTENTINVALID:
     case EQQAPIMESSAGECONTENTNULL:
     case EQQAPIMESSAGETYPEINVALID:
     {
     UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]
     [msgbox show]
     //            [msgbox release]
     
     break
     }
     case EQQAPIQQNOTINSTALLED:
     {
     UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]
     [msgbox show]
     //            [msgbox release]
     
     break
     }
     case EQQAPIQQNOTSUPPORTAPI:
     {
     UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]
     [msgbox show]
     //            [msgbox release]
     
     break
     }
     case EQQAPISENDFAILD:
     {
     UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]
     [msgbox show]
     //            [msgbox release]
     
     break
     }
     default:
     {
     break
     }
     }
     } */
}

extension JKShareManager: WXApiDelegate {
    
    func onResp(_ resp: BaseResp!) {
        
        switch (resp.errCode) {
            
        case Int32(WXSuccess.rawValue):
            JKProgressHUD.showSuccess(withStatus: "分享成功！")
            break;
        case Int32(WXErrCodeUserCancel.rawValue):
            JKProgressHUD.showError(withStatus: "取消操作！")
            break;
        case Int32(WXErrCodeAuthDeny.rawValue):
            JKProgressHUD.showError(withStatus: "授权失败！")
            break;
        case Int32(WXErrCodeUnsupport.rawValue):
            JKProgressHUD.showError(withStatus: "微信不支持！")
            break;
        default:
            JKProgressHUD.showError(withStatus: "分享失败！")
            break;
        }
    }
}

extension JKShareManager: WeiboSDKDelegate {
    
    func didReceiveWeiboRequest(_ request: WBBaseRequest!) {
        
    }
    
    func didReceiveWeiboResponse(_ response: WBBaseResponse!) {
        
        switch (response.statusCode) {
        case .success:
            JKProgressHUD.showSuccess(withStatus: "分享成功！")
            break;
        case .userCancel:
            JKProgressHUD.showError(withStatus: "取消操作！")
            break;
        case .authDeny:
            JKProgressHUD.showError(withStatus: "授权失败！")
            break;
        case .unsupport:
            JKProgressHUD.showError(withStatus: "不支持的请求！")
            break;
        case .unknown:
            JKProgressHUD.showError(withStatus: "未知错误！")
            break;
        case .payFail:
            JKProgressHUD.showError(withStatus: "支付失败！")
            break;
        default:
            JKProgressHUD.showError(withStatus: "分享失败！")
            break;
        }
    }
}
